// basic file operations
#include <stdio.h>
#include "xpmio.h"

// maps 0-63 to chars for use in XPM creation
static char charmap[2] = {'1','0'};

// write an XPM with dimensions height and length to file filename using data
void writeXPM(double **data, int height, int length, char* filename) {
	int i, j;
	FILE *file;
	file = fopen(filename,"w");

	fprintf(file, "%s", "/* XPM */\n");
	fprintf(file, "%s%s%s", "static char * ", filename, "_xpm[] = {\n");
	fprintf(file, "%s%d%s%d%s", "\"", length, " ", height, " 2 1\",\n");
	fprintf(file, "%s", "\"0\tc #000000\",\n");
	fprintf(file, "%s", "\"1\tc #FFFFFF\"");

	for(i = 0; i < height; i++) {
		fprintf(file, "%s", ",\n\"");
		for(j = 0; j < length; j++) {
			if((int)data[j][i] < 0) {
				fprintf(file, "%c", charmap[0]);
			}
			else if((int)data[j][i] > 1) {
				fprintf(file, "%c", charmap[1]);
			}
			else {
				fprintf(file, "%c", charmap[(int)data[j][i]]);
			}
		}
		fprintf(file, "%s", "\"");
	}
	fprintf(file, "%s", "\"};");
	fclose(file);
}
